package com.situ.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class DBUtil {

    //数据源    连接池    javax.sql.DataSource;
    private static DataSource ds;

    static {
        try {
            Properties prop = new Properties();
            prop.load(Thread.currentThread()
                    .getContextClassLoader()
                    .getResourceAsStream("db.properties"));//寻找文件变成流,从src开始
            ds = DruidDataSourceFactory.createDataSource(prop);

        } catch (IOException e) {
            System.out.println("加载db文件失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //执行DML语句的工具方法
    public static int executeDML(String sql, Object... params) {
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = DBUtil.getConnection();

            ps = conn.prepareStatement(sql);

            if (params != null && params.length > 0) {//说明传了参数,要替换?
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }

                int i = ps.executeUpdate();
                return i;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(ps, conn);
        }

        return -1;
    }

    //封装执行统计数量的方法
    public static Long executeCount(String sql,Object... params){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            conn = getConnection();
            ps = conn.prepareStatement(sql);
            if (params != null && params.length > 0){
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i+1,params[i]);
                }
            }
            rs = ps.executeQuery();
            rs.next();
            return rs.getLong(1);
        } catch (SQLException e) {
        } finally {
            close(rs,ps,conn);
        }
        return 0l;
    }


    //封装通用的查询方法  执行通用的DQL方法
    public static <T> List<T> executeDQL(String sql,Class<T> c, Object... params) {

        //创建一个空集合
        List<T> list = new ArrayList<>();

//        c.getFields();//获取变量
//        c.getMethods();//获取方法
//        c.getConstructors();//获取构造

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = getConnection();
            ps = conn.prepareStatement(sql);

            if (params != null && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
            }

            rs = ps.executeQuery();

            //获取结果集的元数据
            ResultSetMetaData rsmd = rs.getMetaData();

            while (rs.next()) {
                T o = c.newInstance();
                //拿到所有成员变量
                /*Field[] fs = c.getDeclaredFields();
                for (Field f : fs) {
                    try {
                        f.setAccessible(true);
                        f.set(o,rs.getObject(f.getName()));
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println(f.getName()+"这一列没赋上值");
                    }
                }*/

                //找到类中的所有的成员变量

                //换一种思路: 找到所有的查询结果集数据,根据每一列的名字去类中找成员变量

                for (int i = 0; i < rsmd.getColumnCount(); i++) {//返回结果集有几列
                    String lable = rsmd.getColumnLabel(i+1);//这一列的名字
                    try {
                        //把lable转换成驼峰再去类中找
                        Field f = c.getDeclaredField(StringUtil.change(lable));
                        f.setAccessible(true);
                        Object value = rs.getObject(i + 1);
                        f.set(o,value);
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println(lable+"这个结果没在类中找到成员变量");
                    }
                }

                list.add(o);
            }

            return list;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(rs, ps, conn);
        }

        return null;
    }

    public static Connection getConnection() {
        try {
            return ds.getConnection();
        } catch (Exception e) {
            return null;
        }
    }

    public static void close(PreparedStatement ps, Connection conn) {
        close(null, ps, conn);
    }

    public static void close(ResultSet rs, PreparedStatement ps, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}
